// 轮播图功能
let slideIndex = 1;
let slideInterval;

// 用户端特定功能

// 页面加载时初始化用户端功能
document.addEventListener('DOMContentLoaded', function() {
    try {
        initSlider();
        bindCarouselControls();
        initNavigation();
        initSmoothScroll();
        initScrollAnimations();
        initResponsiveMenu();
        initFormValidation();
        initLazyLoading();
        initBackToTop();
        initSearch();
    } catch (error) {
        console.error('页面初始化错误:', error);
        showErrorNotification('页面加载失败，请刷新重试');
    }
});

// 初始化轮播图
function initSlider() {
    showSlide(slideIndex);
    startAutoSlide();
}

// 显示指定幻灯片
function showSlide(n) {
    const slides = document.querySelectorAll('.carousel-item');
    
    if (n > slides.length) { slideIndex = 1; }
    if (n < 1) { slideIndex = slides.length; }
    
    // 隐藏所有幻灯片
    slides.forEach(slide => {
        slide.classList.remove('active');
        slide.style.opacity = '0';
        slide.style.zIndex = '1';
    });
    
    // 显示当前幻灯片
    if (slides[slideIndex - 1]) {
        slides[slideIndex - 1].classList.add('active');
        slides[slideIndex - 1].style.opacity = '1';
        slides[slideIndex - 1].style.zIndex = '2';
    }
}

// 切换幻灯片
function changeSlide(n) {
    slideIndex += n;
    showSlide(slideIndex);
    resetAutoSlide();
}

// 跳转到指定幻灯片
function currentSlide(n) {
    slideIndex = n;
    showSlide(slideIndex);
    resetAutoSlide();
}

// 自动轮播
function startAutoSlide() {
    // 移动端禁用自动轮播
    if (window.innerWidth <= 768) {
        return;
    }
    slideInterval = setInterval(() => {
        slideIndex++;
        showSlide(slideIndex);
    }, 5000);
}

// 重置自动轮播
function resetAutoSlide() {
    clearInterval(slideInterval);
    startAutoSlide();
}

// 停止自动轮播（鼠标悬停时）
function stopAutoSlide() {
    clearInterval(slideInterval);
}

// 恢复自动轮播（鼠标离开时）
function resumeAutoSlide() {
    startAutoSlide();
}

// 绑定轮播图控制按钮
function bindCarouselControls() {
    const prevButton = document.querySelector('.carousel-control-prev');
    const nextButton = document.querySelector('.carousel-control-next');
    const carousel = document.querySelector('.carousel');
    
    if (prevButton) {
        prevButton.addEventListener('click', function(e) {
            e.preventDefault();
            changeSlide(-1);
        });
    }
    
    if (nextButton) {
        nextButton.addEventListener('click', function(e) {
            e.preventDefault();
            changeSlide(1);
        });
    }
    
    // 鼠标悬停时暂停自动轮播
    if (carousel) {
        carousel.addEventListener('mouseenter', stopAutoSlide);
        carousel.addEventListener('mouseleave', resumeAutoSlide);
    }
}

// 用户端特定功能绑定

// 导航菜单交互
function initNavigation() {
    const navItems = document.querySelectorAll('.nav-menu > li');
    
    navItems.forEach(item => {
        const link = item.querySelector('a');
        const dropdown = item.querySelector('.dropdown');
        
        if (dropdown) {
            // 鼠标悬停显示下拉菜单
            item.addEventListener('mouseenter', function() {
                dropdown.style.opacity = '1';
                dropdown.style.visibility = 'visible';
                dropdown.style.transform = 'translateY(0)';
                
                // 显示下拉菜单项（带延迟动画）
                const dropdownItems = dropdown.querySelectorAll('a');
                dropdownItems.forEach((item, index) => {
                    setTimeout(() => {
                        item.style.opacity = '1';
                        item.style.transform = 'translateX(0)';
                    }, index * 50);
                });
            });
            
            item.addEventListener('mouseleave', function() {
                dropdown.style.opacity = '0';
                dropdown.style.visibility = 'hidden';
                dropdown.style.transform = 'translateY(-15px)';
                
                // 隐藏下拉菜单项
                const dropdownItems = dropdown.querySelectorAll('a');
                dropdownItems.forEach(item => {
                    item.style.opacity = '0';
                    item.style.transform = 'translateX(-10px)';
                });
            });
        }
    });
}

// 平滑滚动
function initSmoothScroll() {
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                targetSection.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
}

// 滚动动画
function initScrollAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);
    
    // 观察需要动画的元素
    const animatedElements = document.querySelectorAll('.feature-item, .dish-card, .about-content');
    animatedElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });
}

// 响应式菜单
function initResponsiveMenu() {
    const header = document.querySelector('.header .wrap');
    const navMenu = document.querySelector('.nav-menu');
    
    if (!header || !navMenu) return;
    
    // 检查是否已存在菜单按钮
    let menuToggle = document.querySelector('.menu-toggle');
    
    if (!menuToggle) {
        // 创建菜单按钮
        menuToggle = document.createElement('button');
        menuToggle.className = 'menu-toggle';
        menuToggle.innerHTML = '<i class="fas fa-bars"></i>';
        menuToggle.style.cssText = 'display: none; position: absolute; top: 15px; right: 15px; background: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.3); color: white; padding: 8px 12px; border-radius: 4px; cursor: pointer; z-index: 1001; font-size: 18px;';
        header.appendChild(menuToggle);
    }
    
    // 切换菜单显示/隐藏
    function toggleMenu() {
        if (navMenu) {
            navMenu.classList.toggle('active');
            menuToggle.classList.toggle('active');
        }
    }
    
    // 检查屏幕尺寸并设置菜单状态
    function checkScreenSize() {
        if (window.innerWidth <= 768) {
            menuToggle.style.display = 'block';
            if (navMenu) {
                navMenu.style.display = 'none';
            }
        } else {
            menuToggle.style.display = 'none';
            if (navMenu) {
                navMenu.style.display = 'flex';
                navMenu.classList.remove('active');
            }
        }
    }
    
    // 绑定点击事件
    menuToggle.addEventListener('click', toggleMenu);
    
    // 初始检查和窗口大小改变时检查
    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
}

// 表单验证
function initFormValidation() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const inputs = form.querySelectorAll('input[required], textarea[required]');
            let isValid = true;
            
            inputs.forEach(input => {
                if (!input.value.trim()) {
                    isValid = false;
                    input.classList.add('error');
                    showError(input, '此字段为必填项');
                } else {
                    input.classList.remove('error');
                    removeError(input);
                }
                
                // 邮箱验证
                if (input.type === 'email' && input.value) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(input.value)) {
                        isValid = false;
                        input.classList.add('error');
                        showError(input, '请输入有效的邮箱地址');
                    }
                }
                
                // 电话验证
                if (input.type === 'tel' && input.value) {
                    const phoneRegex = /^1[3-9]\d{9}$/;
                    if (!phoneRegex.test(input.value)) {
                        isValid = false;
                        input.classList.add('error');
                        showError(input, '请输入有效的手机号码');
                    }
                }
            });
            
            if (isValid) {
                // 表单提交成功
                showSuccessMessage(form);
            }
        });
    });
}

// 显示错误信息
function showError(input, message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    
    if (!input.parentNode.querySelector('.error-message')) {
        input.parentNode.appendChild(errorDiv);
    }
}

// 移除错误信息
function removeError(input) {
    const errorDiv = input.parentNode.querySelector('.error-message');
    if (errorDiv) {
        errorDiv.remove();
    }
}

// 显示成功消息
function showSuccessMessage(form) {
    const successDiv = document.createElement('div');
    successDiv.className = 'success-message';
    successDiv.innerHTML = `
        <i class="fas fa-check-circle"></i>
        <p>提交成功！我们会尽快与您联系。</p>
    `;
    
    form.innerHTML = '';
    form.appendChild(successDiv);
}

// 显示错误通知
function showErrorNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'error-notification';
    notification.innerHTML = `
        <i class="fas fa-exclamation-triangle"></i>
        <span>${message}</span>
        <button onclick="this.parentElement.remove()">&times;</button>
    `;
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #e74c3c;
        color: white;
        padding: 15px 20px;
        border-radius: 5px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        max-width: 400px;
        animation: slideIn 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    // 5秒后自动消失
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

// 图片懒加载
function initLazyLoading() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                observer.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// 返回顶部按钮
function initBackToTop() {
    const backToTopBtn = document.createElement('button');
    backToTopBtn.className = 'back-to-top';
    backToTopBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
    backToTopBtn.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 50px;
        height: 50px;
        background: #8B4513;
        color: white;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
        z-index: 1000;
    `;
    
    document.body.appendChild(backToTopBtn);
    
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            backToTopBtn.style.opacity = '1';
            backToTopBtn.style.visibility = 'visible';
        } else {
            backToTopBtn.style.opacity = '0';
            backToTopBtn.style.visibility = 'hidden';
        }
    });
    
    backToTopBtn.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 搜索功能
function initSearch() {
    const searchInput = document.querySelector('.search-input');
    const searchResults = document.querySelector('.search-results');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = this.value.toLowerCase();
            
            if (query.length > 2) {
                // 模拟搜索结果
                const results = [
                    { title: '顶级西冷牛排', url: '#steak' },
                    { title: '松露奶油意面', url: '#pasta' },
                    { title: '凯撒沙拉', url: '#salad' }
                ].filter(item => item.title.toLowerCase().includes(query));
                
                displaySearchResults(results);
            } else {
                searchResults.style.display = 'none';
            }
        });
    }
}

// 显示搜索结果
function displaySearchResults(results) {
    const searchResults = document.querySelector('.search-results');
    
    if (!searchResults) return;
    
    searchResults.innerHTML = '';
    
    if (results.length > 0) {
        results.forEach(result => {
            const resultItem = document.createElement('div');
            resultItem.className = 'search-result-item';
            resultItem.innerHTML = `<a href="${result.url}">${result.title}</a>`;
            searchResults.appendChild(resultItem);
        });
        searchResults.style.display = 'block';
    } else {
        searchResults.style.display = 'none';
    }
}

// 窗口大小改变时重新初始化响应式菜单
window.addEventListener('resize', function() {
    const menuToggle = document.querySelector('.menu-toggle');
    const navMenu = document.querySelector('.nav-menu');
    
    if (window.innerWidth <= 768) {
        if (menuToggle) menuToggle.style.display = 'block';
        if (navMenu) navMenu.style.display = 'none';
    } else {
        if (menuToggle) menuToggle.style.display = 'none';
        if (navMenu) {
            navMenu.style.display = 'flex';
            navMenu.classList.remove('active');
        }
    }
});

// 添加一些实用的工具函数
const Utils = {
    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // 获取元素位置
    getOffset: function(element) {
        const rect = element.getBoundingClientRect();
        return {
            top: rect.top + window.pageYOffset,
            left: rect.left + window.pageXOffset
        };
    }
};

// 添加CSS样式到head
const additionalStyles = `
    .menu-toggle {
        display: none;
        background: none;
        border: none;
        color: white;
        font-size: 24px;
        cursor: pointer;
    }
    
    .error-message {
        color: #e74c3c;
        font-size: 14px;
        margin-top: 5px;
    }
    
    .success-message {
        text-align: center;
        padding: 40px;
        background: #d4edda;
        border: 1px solid #c3e6cb;
        border-radius: 5px;
        color: #155724;
    }
    
    .success-message i {
        font-size: 48px;
        color: #28a745;
        margin-bottom: 20px;
    }
    
    .search-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #ddd;
        border-radius: 5px;
        max-height: 200px;
        overflow-y: auto;
        display: none;
        z-index: 1000;
    }
    
    .search-result-item {
        padding: 10px;
        border-bottom: 1px solid #eee;
    }
    
    .search-result-item:last-child {
        border-bottom: none;
    }
    
    .search-result-item a {
        color: #333;
        text-decoration: none;
    }
    
    .search-result-item:hover {
        background: #f8f9fa;
    }
    
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @media (max-width: 768px) {
        .menu-toggle {
            display: block;
        }
        
        .main-nav {
            display: none;
        }
        
        .main-nav.active {
            display: block;
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: #8B4513;
            padding: 20px;
        }
        
        .nav-menu {
            flex-direction: column;
            gap: 10px;
        }
    }
`;

// 添加样式到页面
const styleSheet = document.createElement('style');
styleSheet.textContent = additionalStyles;
document.head.appendChild(styleSheet);

// 添加页面加载动画
window.addEventListener('load', function() {
    document.body.classList.add('loaded');
});

// 添加键盘导航支持
document.addEventListener('keydown', function(e) {
    if (e.key === 'ArrowLeft') {
        changeSlide(-1);
    } else if (e.key === 'ArrowRight') {
        changeSlide(1);
    }
});



